// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  let { action, goodsId, num, userInfo: { openId } } = event

  switch (action) {
    case 'add-cart':
      // 通过商品goodsId和用户openId查找那条购物车记录
      const { data: cartArr } = await db.collection('carts').where({
        goodsId,
        openId
      }).get()
      if (cartArr.length) { // 如果存在记录，进行更新（现在只有数量更新）
        let theCart = cartArr[0]
        let originNum = theCart.num
        return db.collection('carts').where({ _id: theCart._id }).update({
          data: {
            num: originNum + num
          }
        })
      } else { // 不存在购物车记录，就添加一条
        return db.collection('carts').add({
          data: {
            goodsId,
            openId,
            num
          }
        })
      }
      // return db.collection('goods').doc(goodsId).update({
      //   data: {
      //     likes: liked ? num : (data.likes || 0) + num,
      //     liked_userids: likedUserids
      //   }
      // })
      case 'get-carts': // 获取当前用户购物车列表
      let { data: cartsList } = await db.collection('carts').where({
          openId
        }).get()
        let cartsListWithGoodsDetailPromise = cartsList.map(item => db.collection('product1').doc(item.goodsId).get())
        // return db.collection('product1').doc(cartsList[0].goodsId).get()
        let cartsGoodsList = await Promise.all(cartsListWithGoodsDetailPromise)
        return cartsList.map((item, index) => ({
          ...item,
          goods: cartsGoodsList[index].data
        }))
  }

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}